package com.threeti.jiayusms.web.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;

import com.threeti.jiayusms.domain.model.CommunicationFunction;
import com.threeti.jiayusms.domain.service.communicationfunction.CommunicationFunctionQueryService;
import com.threeti.jiayusms.domain.service.communicationfunction.CommunicationFunctionUpdateService;
import com.threeti.jiayusms.domain.util.TemplateIdGenerator;
import com.threeti.jiayusms.framework.util.DynaSearchCriteria;
import com.threeti.jiayusms.framework.util.PagedListHandler;
import com.threeti.jiayusms.framework.web.PagedQueryControllerAdapter;
import com.threeti.jiayusms.web.form.FunctionTemplateForm;

@Controller
@SessionAttributes("FunctionTemplateForm.FunctionTemplateDynaCriteria")
public class FunctionTemplateMainController {

	@Autowired
	private CommunicationFunctionQueryService queryService;

	@Autowired
	private CommunicationFunctionUpdateService updateService;

	@RequestMapping(value="/functionTemplateMain.html")
  public String enterFunctionTemplateMain(HttpServletRequest request,Map modelMap) {
    PagedQueryControllerAdapter pagedHelper = new PagedQueryControllerAdapter();
    int[] index = pagedHelper.getIndex(request);
    PagedListHandler<CommunicationFunction> pagedFunctionTemplates = queryService.findAllFunctionTemplatesByPage(index[0], index[1]);
    pagedHelper.processPage(pagedFunctionTemplates, request);

    modelMap.put("functionTemplates", pagedFunctionTemplates.getPageList());

    return "tracking/functionTemplateMain";
  }

  @RequestMapping(value="/getInsertFunctionByKey.html", method = RequestMethod.GET)
  public void getInsertFunctionByKey(@RequestParam("insertFunctionKey") String insertFunctionKey, HttpServletResponse response) {
    CommunicationFunction function = queryService.findCommunicationFunctionBy(Long.valueOf(insertFunctionKey));
    response.setContentType("text/html");

    PrintWriter out = null;
    try {
      out = new PrintWriter(response.getOutputStream());

      if ("0".equals(function.getFunctionType())) {//数据函数
        if (StringUtils.isNotEmpty(function.getAssociatedField())) {//关联字段非空
          out.write("{" + function.getRelationField() + "}{" + function.getAssociatedField()+"}");
        } else {
          out.write("{" + function.getRelationField() + "}");//function.getRelationField()
        }
      } else {
        out.write("{" + function.getFunctionContent() + "}");
      }
      out.close();
    } catch (IOException e) {
      e.printStackTrace();
      if (out != null) {
        out.write("");
        out.close();
      }
    }
  }

  @RequestMapping(value="/searchFunctionTemplateByPage.html")
  public String searchFunctionTemplate(HttpServletRequest request, @ModelAttribute FunctionTemplateForm form, Map modelMap) {

  	DynaSearchCriteria dynaSearchCriteria = null;

    PagedQueryControllerAdapter pagedHelper = new PagedQueryControllerAdapter();
  	if (pagedHelper.isAnyPageSearch(request)) {
  		dynaSearchCriteria = (DynaSearchCriteria)modelMap.get(FunctionTemplateForm.SESSION_DYNA_CRITERIA_KEY);
  	} else {
      modelMap.put(FunctionTemplateForm.SESSION_DYNA_CRITERIA_KEY, (dynaSearchCriteria = form.buildDynaSearchCriteriaBy("com.threeti.jiayusms.interfaces.FunctionTemplateDynaCriteriaDto")));
  	}

    int[] index = pagedHelper.getIndex(request);
    PagedListHandler<CommunicationFunction> pagedFunctionTemplates = queryService.findFunctionTemplatesByPage(dynaSearchCriteria, index[0], index[1]);
    pagedHelper.processPage(pagedFunctionTemplates, request);

    modelMap.put("functionTemplates", pagedFunctionTemplates.getPageList());

    return "tracking/functionTemplateMain";
  }

  @RequestMapping(value="/newFunctionTemplate.html", method = RequestMethod.POST)
  public String newFunctionTemplate(@ModelAttribute FunctionTemplateForm form, Map modelMap, HttpServletRequest request) {
  	CommunicationFunction function = new CommunicationFunction();
  	function.setFunctionName(form.getFunctionName());
  	function.setDescription(form.getDescription());
  	function.setFunctionType(form.getFunctionTypeSlt());
  	if ("1".equals(form.getFunctionTypeSlt())) {//系统函数
  		function.setFunctionContent(form.getSysFunctionSlt());
    	function.setRelationTable("");
    	function.setRelationField("");
    	function.setAssociatedField("");
  	} else {//数据函数
    	function.setRelationTable(form.getRelationTableSlt());
    	function.setRelationField(form.getRelationFieldSlt());
    	function.setAssociatedField(form.getAssociatedFieldSlt());
  	}

  	CommunicationFunction rtnFunction = updateService.storeCommunicationFunction(function);
  	String templateId = TemplateIdGenerator.generateTempalteIdBy("HS", rtnFunction);
  	rtnFunction.setCustomId(templateId);
  	updateService.storeCommunicationFunction(rtnFunction);

    return "redirect:functionTemplateMain.html";
  }

  @RequestMapping(value="/enterFunctionTemplateEditForm.html", method = RequestMethod.GET)
  public String enterEditMsgTemplate(@RequestParam("updatekey") String functionTemplateId,
                            Map modelMap, HttpServletRequest request) {
  	CommunicationFunction function = queryService.findCommunicationFunctionBy(Long.valueOf(functionTemplateId));

  	modelMap.put("functionTemplate", function);

    return "tracking/editFunctionTemplateForm";
  }

  @RequestMapping(value="/editFunctionTemplate.html", method = RequestMethod.POST)
  public String editMsgTemplate(@ModelAttribute FunctionTemplateForm form, Map modelMap) {

  	CommunicationFunction function = queryService.findCommunicationFunctionBy(Long.valueOf(form.getUpdatekey()));

  	function.setFunctionName(form.getFunctionName());
  	function.setDescription(form.getDescription());
  	function.setFunctionType(form.getFunctionTypeSlt());
  	if ("1".equals(form.getFunctionTypeSlt())) {//系统函数
  		function.setFunctionContent(form.getSysFunctionSlt());
    	function.setRelationTable("");
    	function.setRelationField("");
    	function.setAssociatedField("");
  	} else {//数据函数
    	function.setRelationTable(form.getRelationTableSlt());
    	function.setRelationField(form.getRelationFieldSlt());
    	function.setAssociatedField(form.getAssociatedFieldSlt());
  	}

  	updateService.storeCommunicationFunction(function);

    return "redirect:/functionTemplateMain.html";
  }

  @RequestMapping(value="/removeFunctionTemplate.html", method = RequestMethod.POST)
  public String removeFunctionTemplate(@RequestParam("keys") String pks,
                            Map modelMap, HttpServletRequest request) {
    String[] functionTemplateIds = pks.split(",");
  
    for (int i = 0; i < functionTemplateIds.length; i++) {
      updateService.removeCommunicationFunctionBy(Long.valueOf(functionTemplateIds[i]));
    }
    return "redirect:/functionTemplateMain.html";
  }

  @RequestMapping(value="/quickViewFunction.html", method = RequestMethod.GET)
  public String viewInsertFunction(@RequestParam("type") String type, Map modelMap, HttpServletRequest request) {
    PagedQueryControllerAdapter pagedHelper = new PagedQueryControllerAdapter();
    int[] index = pagedHelper.getIndex(request);
    PagedListHandler<CommunicationFunction> pagedFunctionTemplates = queryService.findAllFunctionTemplatesByPage(index[0], index[1]);
    pagedHelper.processPage(pagedFunctionTemplates, request);

    modelMap.put("type", type);//短信0 语音1
    modelMap.put("functionTemplates", pagedFunctionTemplates.getPageList());

    return "tracking/quickViewFunction";
  }
}
